package com.dobest.utils;

import cn.hutool.core.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author huangy
 * @description
 * @since 2023/2/16 15:10
 **/
public class AESCrypt {

    private static final String CIPHER_MODE = "AES/CBC/PKCS5Padding";

    //默认aes key
    private static final String AES_KEY = "3B0BFF36E170A2A3";

    private static final IvParameterSpec defaultIvSpec = createIV(null);

    public static String encrypt(String content, String key) {
        byte[] encode = encrypt(content.getBytes(), key, null);
        return Base64.encode(encode);
    }

    public static byte[] encrypt(byte[] content, String password, String iv) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);
            cipher.init(Cipher.ENCRYPT_MODE, key, createIV(iv));
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public static String decrypt(String content, String key) {
        byte[] decode = decrypt(Base64.decode(content), key, null);
        return new String(decode);
    }

    public static byte[] decrypt(byte[] content, String password, String iv) {
        return decrypt(content, 0, content == null ? 0 : content.length, password, iv);
    }

    public static byte[] decrypt(byte[] content, int offset, int len, String password, String iv) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);
            cipher.init(Cipher.DECRYPT_MODE, key, createIV(iv));
            return cipher.doFinal(content, offset, len);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    private static SecretKeySpec createKey(String key) {
        byte[] data = null;
        if (key == null) {
            key = "";
        }
        data = getBytes(key);
        return new SecretKeySpec(data, "AES");
    }

    private static IvParameterSpec createIV(String password) {
        byte[] data = null;
        if (password == null) {
            if (defaultIvSpec != null) {
                return defaultIvSpec;
            }
            password = "";
        }
        data = getBytes(password);
        return new IvParameterSpec(data);
    }

    private static byte[] getBytes(String password) {
        StringBuilder sb = new StringBuilder(16);
        sb.append(password);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }
        return sb.toString().getBytes(StandardCharsets.UTF_8);
    }

}
